package org.coder.threadpool.framkwork.core.impl;

import org.coder.threadpool.framkwork.bean.Job;
import org.coder.threadpool.framkwork.bean.TestTask;
import org.coder.threadpool.framkwork.bean.Worker;
import org.coder.threadpool.framkwork.core.ThreadFactory;
import org.coder.threadpool.framkwork.core.ThreadPool;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 简单版本的线程池
 *
 * @author idea
 * @data 2019/9/7
 */
public class DefaultThreadPool implements ThreadPool<Job> {

    private static AtomicInteger workerNum=new AtomicInteger(1);

    private static ThreadFactory threadFactory=new DefaultThreadFactory();

    private static List<Thread> workerList=new ArrayList<>();

    private Worker worker;

    @Override
    public void execute(Job job) {
        for (Thread thread : workerList) {
            try{
                thread.run();
            }catch (Exception e){
                System.err.println("出现异常,异常为:"+e.toString());
            }
        }
    }

    @Override
    public void initWorker(Integer num) {
        workerNum.getAndSet(num);
        for(int i=0;i<num;i++){
           Thread workerThread = threadFactory.createThread(worker);
            workerList.add(workerThread);
        }
        System.out.println("初始化线程结束");
    }

    @Override
    public int getSize() {
        return workerNum.get();
    }

    public Worker getWorker() {
        return worker;
    }

    public DefaultThreadPool setWorker(Worker worker) {
        this.worker = worker;
        return this;
    }

    public static void main(String[] args) {
        DefaultThreadPool defaultThreadPool=new DefaultThreadPool();
        Worker worker=new TestTask();
        defaultThreadPool.setWorker(worker);
        defaultThreadPool.initWorker(10);
        defaultThreadPool.execute(new Job());
    }
}
